package zhihuilan.controlle.wechatMini;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import zhihuilan.common.WxMiniResponse;
import zhihuilan.common.enums.ResultEnum;
import zhihuilan.controlle.BasicController;
import zhihuilan.dto.*;
import zhihuilan.entity.*;
import zhihuilan.params.StaticParam;
import zhihuilan.params.query.MyOrderInvoiceQueryParam;
import zhihuilan.params.query.MyOrderInvoiceStaffQueryParam;
import zhihuilan.params.query.MyPayOrderQueryParam;
import zhihuilan.service.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/app/Order")
public class MyOrderController extends BasicController {


    @Autowired
    private MyPayOrderService myPayOrderService;

    @Autowired
    private MyGoodsService myGoodsService;

    @Autowired
    private MyOrderInvoiceService myOrderInvoiceService;

    @Autowired
    private MyOrderInvoiceStaffService myOrderInvoiceStaffService;

    /**
     * @api {GET} /Order/getOrderList 获取订单列表
     * @apiParam {int}  type 种类
     */
    @PostMapping("getOrderList")
    public WxMiniResponse getOrderList(@RequestBody MyPayOrderQueryParam myPayOrderQueryParam){
        if (!isCheckLogin(myPayOrderQueryParam.getGuid())) {
            //如果用户未登陆，提示用户未登陆信息，并且返回未登陆的枚举编码；
            return WxMiniResponse.error(ResultEnum.UNLOGIN.getKey(), ResultEnum.UNLOGIN.getValue());
        }
        Page<MyPayOrder> wxMiniPageDto = myPayOrderService.getOrderList(myPayOrderQueryParam);
        return WxMiniResponse.ok(wxMiniPageDto);
    }


    /**
     * @api {GET} /Order/getOrderInfo 获取订单详情
     * @apiParam {string}  guid 登录标识
     * @apiParam {int}  orderId 订单编号
     */
    @PostMapping("getOrderInfo")
    public WxMiniResponse getOrderInfo(@RequestBody MyPayOrderQueryParam myPayOrderQueryParam){
        if (!isCheckLogin(myPayOrderQueryParam.getGuid())) {
            //如果用户未登陆，提示用户未登陆信息，并且返回未登陆的枚举编码；
            return WxMiniResponse.error(ResultEnum.UNLOGIN.getKey(), ResultEnum.UNLOGIN.getValue());
        }
        MyPayOrderDto myPayOrderDto =  myPayOrderService.getOrderInfo(myPayOrderQueryParam.getOrderId());
        MyGoods myGoods = myGoodsService.selectGoodsInfoById(myPayOrderDto.getGoodsid());
        myPayOrderDto.setGoods(myGoods);
        return WxMiniResponse.ok(myPayOrderDto);
    }


    /**
     * @api {GET} /Order/setOrderInvoice 设置发票详情
     * @apiParam {string}  guid 登录标识
     * @apiParam {int}  order 订单id
     * @apiParam {String}  username 开票人姓名
     * @apiParam {int}  pid 开票人id
     * @apiParam {int}  tax   发票类型0普通发票  1增值税票
     * @apiParam {String}  remark 备注
     * @apiParam {int}  company 2个人  1企业
     * @apiParam {int}  status 发票状态0-已申请  1-已开  2-拒绝 3-已取消
     * @apiParam {decimal}  amount 开票金额     */
    @PostMapping("setOrderInvoice")
    public WxMiniResponse setOrderInvoice(@RequestBody MyOrderInvoiceQueryParam myOrderInvoiceQueryParam){
        if (!isCheckLogin(myOrderInvoiceQueryParam.getGuid())) {
            //如果用户未登陆，提示用户未登陆信息，并且返回未登陆的枚举编码；
            return WxMiniResponse.error(ResultEnum.UNLOGIN.getKey(), ResultEnum.UNLOGIN.getValue());
        }
        MyPayOrder myPayOrder =  myPayOrderService.getOrderInfoByOrderStatus(myOrderInvoiceQueryParam.getOrder(),2);
        if(myPayOrder==null){
            return WxMiniResponse.error(ResultEnum.ERROR.getKey(),"错误的订单号，或者没有支付，请支付！");
        }
        if(myPayOrder.getInvoice()==1||myPayOrder.getInvoice()==2){
            return WxMiniResponse.error(ResultEnum.ERROR.getKey(),"发票已经申请！");
        }
        if(myPayOrder.getAmount().equals(myOrderInvoiceQueryParam.getAmount())){
            return WxMiniResponse.error(ResultEnum.ERROR.getKey(),"开票金额不正确！");
        }
        Integer updateNum = myPayOrderService.updateOrderByOrder(myOrderInvoiceQueryParam.getOrder());
        if(updateNum==0){
            return WxMiniResponse.error(ResultEnum.ERROR.getKey(),"未知错误，请联系管理员");
        }
        MyOrderInvoice myOrderInvoice =  myOrderInvoiceService.selectOrderInvoiceByOrder(myPayOrder.getOrder());
        if(myOrderInvoice!=null){
            return WxMiniResponse.error(ResultEnum.ERROR.getKey(),"已申请");
        }
        MyOrderInvoice orderInvoice = new MyOrderInvoice();
        orderInvoice.setOrder(myPayOrder.getOrder());
        orderInvoice.setOrderId(Integer.parseInt(myOrderInvoiceQueryParam.getOrder()));
        orderInvoice.setPid(myOrderInvoiceQueryParam.getPid());
        orderInvoice.setType(myPayOrder.getType());
        orderInvoice.setStaffId(currentStaff.getId());
        orderInvoice.setUserName(myOrderInvoiceQueryParam.getUsername());
        orderInvoice.setRemark(myOrderInvoiceQueryParam.getRemark());
        orderInvoice.setStatus(myOrderInvoiceQueryParam.getStatus());
        orderInvoice.setTax(myOrderInvoiceQueryParam.getTax());
        orderInvoice.setAmount(myOrderInvoiceQueryParam.getAmount());
        orderInvoice.setPayType(myPayOrder.getType());
        orderInvoice.setGoodsId(myPayOrder.getGoodsid());
        orderInvoice.setCreateTime(new Date().getTime()/1000);
        orderInvoice.setCreateUser(currentStaff.getId().toString());
        orderInvoice.setCompany(myOrderInvoiceQueryParam.getCompany());
        Integer s =  myOrderInvoiceService.insertOrderInvoice(orderInvoice);
        if(s==0){
            return WxMiniResponse.error(2024,"申请失败，请联系客服！");
        }
        return WxMiniResponse.ok("申请成功，请等待开票");
    }

    @Autowired
    private MyStaffService myStaffService;

    /**
     * @api {GET} /Order/getOrderInvoiceInfo 获取发票详情
     * @apiParam {string}  guid 登录标识
     * @apiParam {int}  orderId 订单id
     */
    @PostMapping("getOrderInvoiceInfo")
    public WxMiniResponse getOrderInvoiceInfo(@RequestBody MyPayOrderQueryParam myPayOrderQueryParam){
        if (!isCheckLogin(myPayOrderQueryParam.getGuid())) {
            //如果用户未登陆，提示用户未登陆信息，并且返回未登陆的枚举编码；
            return WxMiniResponse.error(ResultEnum.UNLOGIN.getKey(), ResultEnum.UNLOGIN.getValue());
        }
        MyOrderInvoice myOrderInvoice =  myOrderInvoiceService.selectOrderInvoiceByOrderId(myPayOrderQueryParam.getOrderId());
        if(myOrderInvoice==null){
            return WxMiniResponse.error(ResultEnum.ERROR.getKey(),"错误的orderid！");
        }
        MyOrderInvoiceDto myOrderInvoiceDto = new MyOrderInvoiceDto();
        MyOrderInvoiceStaffDto myOrderInvoiceStaffDto  = new MyOrderInvoiceStaffDto();
        MyOrderInvoiceStaff myOrderInvoiceStaff =  myOrderInvoiceStaffService.selectOrderInvoiceStaffById(myOrderInvoice.getPid());
        BeanUtils.copyProperties(myOrderInvoice,myOrderInvoiceDto);
        BeanUtils.copyProperties(myOrderInvoiceStaff,myOrderInvoiceStaffDto);
        myOrderInvoiceDto.setStaff(myOrderInvoiceStaffDto);
//        myOrderInvoice.setStaff(myStaffService.selectMyStaffById(MyOrderInvoice.));
        return WxMiniResponse.ok(myOrderInvoiceDto);
    }


    /**
     * @api {GET} /Order/setOrderInvoiceStastus 开发票
     * @apiVersion 1.0.0
     * @apiName setOrderInvoice
     * @apiGroup Order
     * @apiParam {string}  guid 登录标识
     * @apiParam {int}  id 订单id
     */
    @PostMapping("setOrderInvoiceStastus")
    public WxMiniResponse setOrderInvoiceStastus(@RequestBody MyOrderInvoiceQueryParam myOrderInvoiceQueryParam){
        if (!isCheckLogin(myOrderInvoiceQueryParam.getGuid())) {
            //如果用户未登陆，提示用户未登陆信息，并且返回未登陆的枚举编码；
            return WxMiniResponse.error(ResultEnum.UNLOGIN.getKey(), ResultEnum.UNLOGIN.getValue());
        }

        MyOrderInvoice myOrderInvoice =  myOrderInvoiceService.selectOrderInvoiceByIdStatus(myOrderInvoiceQueryParam.getId(),0);
        if(myOrderInvoice==null){
            WxMiniResponse.error(ResultEnum.ERROR.getKey(),"订单不存在");
        }
        myOrderInvoice = new MyOrderInvoice();
        myOrderInvoice.setStatus(3);
        myOrderInvoice.setUpdateTime(new Date().getTime()/1000);
        myOrderInvoice.setUpdateUser(currentStaff.getId().toString());
        MyOrderInvoice orderInvoice =  myOrderInvoiceService.updateOrderInvoiceByIdStatus(myOrderInvoiceQueryParam.getId(),0,myOrderInvoice);
        return WxMiniResponse.ok(orderInvoice);
    }


    /**
     * @api {GET} /Order/setOrderInvoiceStaff 设置开票人详情
     * @apiParam {string}  guid 登录标识
     * @apiParam {string}  title 发票抬头
     * @apiParam {string}  address 地址
     * @apiParam {string}  email 收件email
     * @apiParam {string}  phone 电话
     * @apiParam {string}  bankname 开户行
     * @apiParam {string}  bankno 银行卡
     * @apiParam {string}  remark 备注
     * @apiParam {string}  taxid 纳税人识别 号
     * @defualt {int}  default 设置是否默认0不默认  1默认
     * @defualt {int}  type 1企业  2个人
     */
    @PostMapping("setOrderInvoiceStaff")
    public WxMiniResponse setOrderInvoiceStaff(@RequestBody MyOrderInvoiceStaffQueryParam myOrderInvoiceStaffQueryParam){
        if (!isCheckLogin(myOrderInvoiceStaffQueryParam.getGuid())) {
            //如果用户未登陆，提示用户未登陆信息，并且返回未登陆的枚举编码；
            return WxMiniResponse.error(ResultEnum.UNLOGIN.getKey(), ResultEnum.UNLOGIN.getValue());
        }
        System.out.println(myOrderInvoiceStaffQueryParam);
        MyOrderInvoiceStaff myOrderInvoiceStaff = new MyOrderInvoiceStaff();
        BeanUtils.copyProperties(myOrderInvoiceStaffQueryParam,myOrderInvoiceStaff);
        myOrderInvoiceStaff.setStaffId(currentStaff.getId().toString());
        myOrderInvoiceStaff.setCreateTime(new Date().getTime()/1000);
        myOrderInvoiceStaff.setCreateUser(currentStaff.getId().toString());
        if(myOrderInvoiceStaffQueryParam.getDefaultStr()!=null&&myOrderInvoiceStaffQueryParam.getDefaultStr()==1){
            myOrderInvoiceStaffService.updateOrderInvoiceDefaultByStaff(currentStaff.getId());
        }
        System.out.println(myOrderInvoiceStaffQueryParam);
        if(myOrderInvoiceStaffQueryParam.getId()==null){
             myOrderInvoiceStaffService.insertNew(myOrderInvoiceStaff);
            return WxMiniResponse.ok();
        }else{
            MyOrderInvoiceStaff reInvoice = myOrderInvoiceStaffService.updateOrderInvoiceStaffById(myOrderInvoiceStaff);
            return WxMiniResponse.ok(reInvoice);
        }
    }


    /**
     * @api {GET} /Order/getOrderInvoiceList 获取发票列表
     * @apiVersion 1.0.0
     * @apiName getOrderInvoiceList
     * @apiGroup Order
     * @apiParam {string}  guid 登录标识
     * @apiParam {int}  page 第几页
     * @apiParam {int}  pagesize 一页多少条数据
     */
    @PostMapping("getOrderInvoiceList")
    public WxMiniResponse getOrderInvoiceList(@RequestBody MyOrderInvoiceQueryParam myOrderInvoiceQueryParam){
        if (!isCheckLogin(myOrderInvoiceQueryParam.getGuid())) {
            //如果用户未登陆，提示用户未登陆信息，并且返回未登陆的枚举编码；
            return WxMiniResponse.error(ResultEnum.UNLOGIN.getKey(), ResultEnum.UNLOGIN.getValue());
        }
        List<MyOrderInvoice> list = myOrderInvoiceService.selectOrderInvoiceList(myOrderInvoiceQueryParam);

            List<MyOrderInvoiceDto> convertList =  list.stream().map(po->{
                MyOrderInvoiceDto myOrderInvoiceDto = new MyOrderInvoiceDto();
                BeanUtils.copyProperties(po, myOrderInvoiceDto);
                myOrderInvoiceDto.setStaff(myOrderInvoiceStaffService.selectOrderInvoiceStaffById(po.getPid()));
                return myOrderInvoiceDto;
            }).collect(Collectors.toList());
        BigDecimal  totalAmount = myPayOrderService.totalAmount(currentStaff.getGuid());
        Map map = new HashMap();
        map.put("totalfee",totalAmount);
        map.put("invoice",convertList);
        return WxMiniResponse.ok(map);
    }

    /**
     * @api {GET} /Order/getOrderInvoiceStaff 获取开票人详情
     * @apiParam {string}  guid 登录标识
     * @apiParam {string}  id 开票人
     */
    @PostMapping("getOrderInvoiceStaff")
    public WxMiniResponse getOrderInvoiceStaff(@RequestBody StaticParam staticParam){
        if (!isCheckLogin(staticParam.getGuid())) {
            //如果用户未登陆，提示用户未登陆信息，并且返回未登陆的枚举编码；
            return WxMiniResponse.error(ResultEnum.UNLOGIN.getKey(), ResultEnum.UNLOGIN.getValue());
        }
        MyOrderInvoiceStaff myOrderInvoiceStaff = myOrderInvoiceStaffService.selectOrderInvoiceStaffById(staticParam.getId());
        if(myOrderInvoiceStaff==null){
            return WxMiniResponse.error(ResultEnum.ERROR.getKey(),"id不对,请联系管理员！");
        }
        MyOrderInvoiceStaffDto myOrderInvoiceStaffDto = new MyOrderInvoiceStaffDto();
        BeanUtils.copyProperties(myOrderInvoiceStaff,myOrderInvoiceStaffDto);
        return WxMiniResponse.ok(myOrderInvoiceStaffDto);
    }


    /**
     * @api {GET} /Order/getOrderInvoiceStaffList 获取开票人
     * @apiParam {string}  guid 登录标识
     * @apiParam {string}  type 票类型
     */
    @PostMapping("getOrderInvoiceStaffList")
    public WxMiniResponse getOrderInvoiceStaffList(@RequestBody StaticParam staticParam){
        if (!isCheckLogin(staticParam.getGuid())) {
            //如果用户未登陆，提示用户未登陆信息，并且返回未登陆的枚举编码；
            return WxMiniResponse.error(ResultEnum.UNLOGIN.getKey(), ResultEnum.UNLOGIN.getValue());
        }
       List<MyOrderInvoiceStaff> list =  myOrderInvoiceStaffService.OrderInvoiceStaffList(currentStaff.getId(),staticParam.getType());
        List<MyOrderInvoiceStaffDto> convertList =  list.stream().map(po->{
            MyOrderInvoiceStaffDto myOrderInvoiceDto = new MyOrderInvoiceStaffDto();
            BeanUtils.copyProperties(po, myOrderInvoiceDto);
            return myOrderInvoiceDto;
        }).collect(Collectors.toList());
        return WxMiniResponse.ok(convertList);
    }

    /**
     * @api {GET} /Order/delOrderInvoiceStaff  删除开票人
     * @apiParam {string}  guid 登录标识
     * @apiParam {int}  id 登陆人id
     */
    @PostMapping("delOrderInvoiceStaff")
    public WxMiniResponse delOrderInvoiceStaff(@RequestBody  StaticParam staticParam){
        if (!isCheckLogin(staticParam.getGuid())) {
            //如果用户未登陆，提示用户未登陆信息，并且返回未登陆的枚举编码；
            return WxMiniResponse.error(ResultEnum.UNLOGIN.getKey(), ResultEnum.UNLOGIN.getValue());
        }
        MyOrderInvoiceStaff myOrderInvoiceStaff = myOrderInvoiceStaffService.selectOrderInvoiceStaffById(staticParam.getId());
        if(myOrderInvoiceStaff==null){
            return WxMiniResponse.error(ResultEnum.ERROR.getKey(),"请输入正确的id,或请联系管理员！");
        }
        Integer res = myOrderInvoiceStaffService.delOrderInvoiceStaff(staticParam.getId());
        if(res==null){
            return WxMiniResponse.error(ResultEnum.ERROR.getKey(),"没有正确删除,或请联系管理员！");
        }
        return WxMiniResponse.ok("删除成功！");
    }
}
